package com.cdqidi.core.weixinmanager.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author sjk
 */
@Slf4j
public class Sign {
    private Sign() {

    }

    public static Map<String, String> sign(String jsApiTicket, String url) {
        Map<String, String> ret = new HashMap<>(5);
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();
        String urlParams = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(urlParams.getBytes(StandardCharsets.UTF_8));
            String signature = byteToHex(crypt.digest());
            ret.put("url", url);
            ret.put("jsapi_ticket", jsApiTicket);
            ret.put("nonceStr", nonceStr);
            ret.put("timestamp", timestamp);
            ret.put("signature", signature);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


}
